package org.chen.q2;

import java.io.*;
import java.nio.file.Files;

/**
 * @author Charles
 * 自定义类加载器
 */
public class MyClassLoader extends ClassLoader {
    private String classpath = MyClassLoaderTest.class.getResource("/").getPath();
    private String suffix = ".xlass";

    public MyClassLoader() {}
    public MyClassLoader(String classpath) {
        this.classpath = classpath;
    }
    public MyClassLoader(String classpath,String suffix) {
        this.classpath = classpath;
        this.suffix = suffix;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            String fullPath = classpath + name + suffix;
            File file = new File(fullPath);
            byte[] bytes = Files.readAllBytes(file.toPath());
            for (int i =0 ;i < bytes.length;i++){
                bytes[i] =  (byte) (~bytes[i]);
            }
            return defineClass(name,bytes,0,bytes.length);
        } catch (IOException e) {
            throw new ClassNotFoundException(e.getMessage());
        }
    }
}
